<?php

namespace app\admin\controller;

use app\admin\model\Menu;
use app\admin\model\Role;

use think\Cache;
use think\Controller;
use think\Request;

class Base extends Controller
{

    protected $admin = ''; //Admin
    protected $menu = null; //Current Menu Obj
    protected $model = ''; //Model Name
    protected $exceptAction = []; // 不需要验证权限的action
    protected $accessAction = ['index', 'add']; // 需要验证权限的action
    protected $access = [];


    public function _initialize(){
        parent::_initialize();

        $module = $this->request->module();
        $controller = $this->request->controller();
        $action = $this->request->action();

        // 获取当前菜单
        $this->menu = Menu::where('url', $module . '/' . $controller . '/' . $action)->find();
        if($this->menu){
            $this->assign('title', $this->menu->name);
        }

        // 获取当前model
        $this->model = $this->request->controller();
        $this->assign('model', $this->model);

        $this->authCheck();

        // Get menu (初始化后台菜单)
        $this->assign('sidebar', $this->menuHtml($this->menuJson()));
    }

    private function authCheck(){
        $session_admin = session('ADMIN');
        if(empty($session_admin->id)){
            if($this->request->isAjax()){
                $this->error('您没有访问权限！', url('/login'));
            }else{
                $this->redirect('/login');
            }
        }else{
            $this->admin = $session_admin;
            if(!$this->checkAccess()){
                $this->error('您没有访问权限！');
            }

            $this->assign('adminInfo', $session_admin);
        }
    }

    /**
     * 权限检查
     * @return bool
     */
    private function checkAccess() {
        // 0-超级管理员
        if($this->admin->type == 0) {
            return true;
        }

        $roleIds = db('roleuser')->where(['operatorId' => $this->admin->id])->field('roleId')->select();
        $roleIds = array_column($roleIds, 'roleId');
        $access = Role::whereIn('id', $roleIds)->field('access')->select();
        $access = array_column($access, 'access');
        $accessStr = implode(',', $access);
        $access = array_unique(explode(',', $accessStr));
        $this->access = $access;

        if($this->menu){
            if(!in_array($this->menu->id, $this->access)){
                //$this->error('您没有访问权限！');
                $this->redirect('admin/error/noaccess');
            }
        }

        return true;
    }

    /**
     * Cache menu
     *
     * @param null $data
     * @return bool|null
     */
    public function menuCache($data = null) {
        if (empty($data)) {
            $data = Menu::getTree(0);
            // 缓存
            Cache::set('admin_menu', $data, 3600*6);
        } else {
            Cache::set('admin_menu', $data, 3600*6);
        }
        return $data;
    }

    /**
     * 菜单树状结构集合
     */
    public function menuJson() {
        $menu = Cache::get('admin_menu');
        if (!$menu) {
            $menu = $this->menuCache();
        }
        return $menu;
    }

    /**
     * 菜单
     * @param $menus
     * @return string
     */
    public function menuHtml($menus) {
        if($menus){
            //$this->access = explode(',', $this->admin->menuId);
            $subMenu = function ($menus, $level = 0) use (&$subMenu) {
                $output = '';
                foreach($menus as $menu){
                    // 检查菜单权限
                    /*if ($this->admin->id != '0' && !in_array($menu['id'], $this->access)) {
                        continue;
                    }*/

                    if(empty($menu['items'])){
                        $output .= '<li class="">';
                        $output .= '<a _href="'.$menu['url'].'" class="" target="'.$menu['target'].'">';
                        $output .= $menu['icon'];
                        $output .= '<cite>'.lang($menu['name']).'</cite>';
                        $output .= '</a>';
                        $output .= '</li>';
                    }else{
                        $output .= '<li class="">';
                        $output .= '<a _href="'.$menu['url'].'" class="" target="'.$menu['target'].'">';
                        $output .= $menu['icon'];
                        $output .= '<cite>'.lang($menu['name']).'</span>';
                        $output .= '<i class="iconfont nav_right">&#xe697;</i>';
                        $output .= '</a>';
                        $output .= '<ul class="sub-menu">';
                        $output .= $subMenu($menu['items'], $level + 1);
                        $output .= '</ul>';
                        $output .= '</li>';
                    }
                }
                return $output;
            };
            $output = $subMenu($menus);

            return $output;
        }
    }

    /**
     * 删除
     */
    public function del(Request $request){
        $model = model($this->model);
        if($request->isPost()){
            $param = $request->param();
            $id = $request->param('id');
            if(isset($_POST['ids'])){
                // 删除多条
                $ids = $param['ids'];
                $result = $model->whereIn('id', $ids)->delete();
            }else if($id){
                // 删除一条
                $result = $model->where('id', $id)->delete();
            }

            if($result === false){
                return show(config('status.error_code'),'删除失败','删除失败');
            }else{
                return show(config('status.success_code'),'删除成功','删除成功');
            }
        }
    }

}